package com.practices2.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;

public class ImageUtil {
	/*
	 * 按比例缩放图片
	 * 
	 * @para sx，sy对应源图宽高的缩放比例 eg. sx=0.1,sy=0.1 表示缩小到原图0.1倍
	 * 
	 * @return 大小为参数设定比例的Bitmap
	 */
	public static Bitmap getScaledBitmap4(Bitmap srcBitmap, float sx, float sy) {
		int bmpWidth = srcBitmap.getWidth();
		int bmpHeight = srcBitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.postScale(sx, sy);
		Bitmap resizedBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
		return resizedBitmap;
	}

	/*
	 * 按指定比例缩放源图后绘制一特定大小图片
	 * 
	 * @para sx，sy对应源图宽高的缩放比例
	 * 
	 * @para theWidth,theHeight 指定的目标Bitmap大小
	 * 
	 * @return 大小为(theWidth,theHeight)的Bitmap
	 */
	public static Bitmap getScaledBitmap3(Bitmap srcBitmap, float sx, float sy, int theWidth, int theHeight) {
		Matrix matrix = new Matrix();
		matrix.setScale(sx, sy);
		Bitmap bitmap = Bitmap.createBitmap(theWidth, theHeight, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
		canvas.drawBitmap(srcBitmap, matrix, new Paint(Paint.DITHER_FLAG));
		return bitmap;
	}

	/*
	 * 按比例缩放到源图后绘制一特定大小图片
	 * 
	 * @para theWidth,theHeight 指定的目标Bitmap大小
	 * 
	 * @return 大小为(theWidth,theHeight)的Bitmap
	 */
	public static Bitmap getScaledBitmap2(Bitmap srcBitmap, int theWidth, int theHeight) {
		Matrix matrix = new Matrix();
		matrix.setScale(((float) theWidth) / srcBitmap.getWidth(), ((float) theHeight) / srcBitmap.getHeight());
		Bitmap bitmap = Bitmap.createBitmap(theWidth, theHeight, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
		canvas.drawBitmap(srcBitmap, matrix, new Paint(Paint.DITHER_FLAG));
		return bitmap;
	}

	/*
	 * 缩小图片：按比例将源图缩小成宽和高分别小于maxWidth和maxHeight的图 （计算出缩放后的具体宽高后，再创建bitmap）
	 * 
	 * @para maxWidth,maxHeight最大宽高
	 * 
	 * @return 宽高不超过(maxWidth,maxHeight)的等比例图片
	 */
	public static Bitmap getScaledBitmap1(Bitmap srcBitmap, int maxWidth, int maxHeight) throws OutOfMemoryError {
		int bmpWitdh = srcBitmap.getWidth();
		int bmpHeight = srcBitmap.getHeight();
		if (bmpWitdh > 0 && bmpHeight > 0) {
			int targetWidth = maxWidth;
			int targetHeight = maxHeight;
			int newWidth = 0, newHeight = 0;

			if (bmpWitdh == targetWidth) {
				newWidth = targetWidth;
				newHeight = bmpHeight;

			} else if (bmpWitdh < targetWidth) {
				newWidth = targetWidth;
				newHeight = bmpHeight * newWidth / bmpWitdh;
			} else {
				newWidth = targetWidth;
				newHeight = bmpHeight * newWidth / bmpWitdh;
			}
			if (newHeight > targetHeight) {
				bmpWitdh = newWidth;
				bmpHeight = newHeight;
				newHeight = targetHeight;
				newWidth = bmpWitdh * newHeight / bmpHeight;
			}

			return Bitmap.createScaledBitmap(srcBitmap, newWidth, newHeight, true);
		}
		return null;
	}

	/*
	 * 按指定高度缩放图片
	 * 
	 * @para theHeight 指定目标图片的高
	 * 
	 * @return 高为theHeight、宽为等比例的bitmap
	 */
	public static Bitmap getScaledBitmapByHeight(Bitmap srcBitmap, int theHeight) throws OutOfMemoryError {
		int newWidth = srcBitmap.getWidth() * theHeight / srcBitmap.getHeight();
		return Bitmap.createScaledBitmap(srcBitmap, newWidth, theHeight, true);
	}

	/*
	 * 按指定高度缩放图片,并限定最大宽度
	 * 
	 * @para theHeight 指定目标图片的高
	 * 
	 * @para maxWidth 最大宽度
	 * 
	 * @return 高为theHeight、宽为等比例但不超过maxWidth的bitmap
	 */
	public static Bitmap getScaledBitmapByHeight(Bitmap srcBitmap, int theHeight, int maxWidth) throws OutOfMemoryError {
		int newWidth = srcBitmap.getWidth() * theHeight / srcBitmap.getHeight();
		if (newWidth > maxWidth) {
			newWidth = maxWidth;
		}
		return Bitmap.createScaledBitmap(srcBitmap, newWidth, theHeight, true);
	}

	public static Drawable BitmapToDrawable(Bitmap bmp) {
		return new BitmapDrawable(bmp);
	}

	public static String getImagePathFromUri(Context ctx, Uri uri) {
		String result;
		Cursor cursor = ctx.getContentResolver().query(uri, null, null, null, null);
		if (cursor == null) {
			return uri.getPath();
		}
		cursor.moveToFirst();
		result = cursor.getString(1);
		cursor.close();
		return result;
	}

	/**
	 * 
	 * @Title: loadScalledBitmapInaccurate
	 * @Description: 如果是大图，则缩小
	 * @param @param path 源文件地址
	 * @param @param targetWidth 生成后bitmap的宽度
	 * @param @param targetHeight 生成后bitmap的高度
	 * @return Bitmap
	 * @throws
	 */
	public static Bitmap loadScalledBitmapInaccurate(String path, int targetWidth, int targetHeight) {

		Bitmap bitmap = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);

		// if (options.outHeight * options.outWidth > 1000000) {
		// if (U.debugFlag){
		// U.dout("[loadScalledBitmapInaccurate] : scalled!!!");
		// }
		int scale = 1;
		if ((targetWidth > 0) && (targetHeight > 0)) {
			int maxSize = targetHeight >= targetWidth ? targetHeight : targetWidth;

			if (options.outHeight > targetHeight || options.outWidth > targetWidth) {
				scale = (int) Math.pow(2, (int) Math.round(Math.log(maxSize / (double) Math.max(options.outHeight, options.outWidth)) / Math.log(0.5)));
			} else {
				scale = (int) Math.min(Math.floor(options.outWidth / targetWidth), Math.floor(options.outHeight / targetHeight));
			}
		}
		if (scale <= 0) {
			scale = 1;
		}
		options.inSampleSize = scale;
		options.inJustDecodeBounds = false;
		try {
			bitmap = BitmapFactory.decodeFile(path, options);
		} catch (OutOfMemoryError e) {
			// U.dout("[ImageUtil] loadScalledBitmapInaccurate OutOfMemoryError");
		}
		// }else {
		// try {
		// bitmap = BitmapFactory.decodeFile(path);
		// } catch (OutOfMemoryError e) {
		// }
		// }
		return bitmap;
	}

	/**
	 * 
	 * @Title: rotate
	 * @Description: 图片的旋转后生成新的bitmap
	 * @param @param b
	 * @param @param degrees 旋转角度
	 * @return Bitmap 返回类型
	 * @throws
	 */
	public static Bitmap rotate(Bitmap b, int degrees) {
		// if (U.debugFlag) {
		// U.dout("[ImageUtil] rotate: " + degrees);
		// }
		if (degrees != 0 && b != null) {
			Matrix m = new Matrix();
			m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
			try {
				Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
				if (b != b2) {
					b.recycle();
					b = b2;
				}
			} catch (OutOfMemoryError ex) {
			}
		}
		return b;
	}

	public static Bitmap drawableToBitmap(NinePatchDrawable npd) {
		Rect rc = npd.getBounds();
		Bitmap bitmap = Bitmap.createBitmap(rc.width(), rc.height(), Config.ARGB_4444);
		Canvas canvas = new Canvas(bitmap);
		npd.draw(canvas);
		return bitmap;
	}

	// watermark
	// try {
	// ImageView img=(ImageView) findViewById(R.id.test_img_file);
	// //获取从本地获取的文件路径，用FileInputstream读入文件，并将图片文件转换成位图
	// Bundle bundle=getIntent().getExtras();
	// String path=bundle.getString("test");
	// FileInputStream fa=new FileInputStream(path);
	// Bitmap bm=BitmapFactory.decodeStream(fa);//原图
	// Bitmap wm=BitmapFactory.decodeResource(getResources(),
	// R.drawable.wate_market);//水印
	// //将creatBitmap()方法的返回值(返回位图)放到图片控件显示
	// img.setImageBitmap(createBitMap(bm,wm));
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	// });
	// }
	// private Bitmap createBitMap(Bitmap src,Bitmap wmsrc){
	// /**
	// * 水印制作方法
	// */
	// String tag="xx";
	// Log.d(tag, "开始了，画图");
	// if(src==null){
	// return null;
	// }
	// int w=src.getWidth();
	// int h=src.getHeight();
	// int wmw=wmsrc.getWidth();
	// int wmh=wmsrc.getHeight();
	// //create the new bitmap
	// Bitmap newb=Bitmap.createBitmap(w,h,Config.ARGB_8888);//创建一个底图
	// Canvas cv=new Canvas(newb);
	// //将底图画进去
	// cv.drawBitmap(src, 0, 0,null);//在0,0坐标开始画入src
	// //讲水印画进去
	// cv.drawBitmap(wmsrc, w-wmw+5, h-wmh+5, null);
	// //保存图片
	// cv.save(Canvas.ALL_SAVE_FLAG);
	// cv.restore();
	// return newb;
	// s
	// }
	// }
	private static float[] carray = new float[20];
	/**
	 * 处理图片的工具类.
	 */

	public static final int LEFT = 0;
	public static final int RIGHT = 1;
	public static final int TOP = 3;
	public static final int BOTTOM = 4;

	/** */
	/**
	 * 图片去色,返回灰度图片
	 * 
	 * @param bmpOriginal
	 *            传入的图片
	 * @return 去色后的图片
	 */
	public static Bitmap toGrayscale(Bitmap bmpOriginal) {
		int width, height;
		height = bmpOriginal.getHeight();
		width = bmpOriginal.getWidth();
		Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
		Canvas c = new Canvas(bmpGrayscale);
		Paint paint = new Paint();
		ColorMatrix cm = new ColorMatrix();
		cm.setSaturation(0);
		ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
		paint.setColorFilter(f);
		c.drawBitmap(bmpOriginal, 0, 0, paint);
		return bmpGrayscale;
	}

	/**
	 * 去色同时加圆角
	 * 
	 * @param bmpOriginal
	 *            原图
	 * @param pixels
	 *            圆角弧度
	 * @return 修改后的图片
	 */
	public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
		return toRoundCorner(toGrayscale(bmpOriginal), pixels);
	}

	/**
	 * 把图片变成圆角
	 * 
	 * @param bitmap
	 *            需要修改的图片
	 * @param pixels
	 *            圆角的弧度
	 * @return 圆角图片
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 使圆角功能支持BitampDrawable
	 * 
	 * @param bitmapDrawable
	 * @param pixels
	 * @return
	 */
	public static BitmapDrawable toRoundCorner(BitmapDrawable bitmapDrawable, int pixels) {
		Bitmap bitmap = bitmapDrawable.getBitmap();
		bitmapDrawable = new BitmapDrawable(toRoundCorner(bitmap, pixels));
		return bitmapDrawable;
	}

	/**
	 * 读取路径中的图片，然后将其转化为缩放后的bitmap，并覆盖掉
	 * 
	 * @param path
	 */
	public static void saveBefore(String path) {

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 获取这个图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回bm为空
		options.inJustDecodeBounds = false;
		// 计算缩放比
		int be = (int) (options.outHeight / (float) 200);
		if (be <= 0)
			be = 1;
		options.inSampleSize = 2; // 图片长宽各缩小二分之一
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
		bitmap = BitmapFactory.decodeFile(path, options);
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		System.out.println(w + " " + h);
		// savePNG_After(bitmap,path);
		saveJPGE_After(bitmap, path);

	}

	/**
	 * 保存图片为PNG
	 * 
	 * @param bitmap
	 * @param name
	 *            保存文件的位置
	 */
	public static void savePNG_After(Bitmap bitmap, String name) {
		File file = new File(name);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存图片为JPEG
	 * 
	 * @param bitmap
	 * @param path
	 *            保存文件的位置
	 */
	public static void saveJPGE_After(Bitmap bitmap, String path) {
		File file = new File(path);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
				out.flush();
				out.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 水印
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap createBitmapForWatermark(Bitmap src, Bitmap watermark) {
		if (src == null) {
			return null;
		}
		int w = src.getWidth();
		int h = src.getHeight();
		int ww = watermark.getWidth();
		int wh = watermark.getHeight();
		// create the new blank bitmap
		Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
		Canvas cv = new Canvas(newb);
		// draw src into
		cv.drawBitmap(src, 0, 0, null);// 在 0，0坐标开始画入src
		// draw watermark into
		cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// 在src的右下角画入水印
		// save all clip
		cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		// store
		cv.restore();// 存储
		return newb;
	}

	/**
	 * 图片合成
	 * 
	 * @return
	 */
	public static Bitmap potoMix(int direction, Bitmap... bitmaps) {
		if (bitmaps.length <= 0) {
			return null;
		}
		if (bitmaps.length == 1) {
			return bitmaps[0];
		}
		Bitmap newBitmap = bitmaps[0];
		// newBitmap = createBitmapForFotoMix(bitmaps[0],bitmaps[1],direction);
		for (int i = 1; i < bitmaps.length; i++) {
			newBitmap = createBitmapForFotoMix(newBitmap, bitmaps[i], direction);
		}
		return newBitmap;
	}

	private static Bitmap createBitmapForFotoMix(Bitmap first, Bitmap second, int direction) {
		if (first == null) {
			return null;
		}
		if (second == null) {
			return first;
		}
		int fw = first.getWidth();
		int fh = first.getHeight();
		int sw = second.getWidth();
		int sh = second.getHeight();
		Bitmap newBitmap = null;
		if (direction == LEFT) {
			newBitmap = Bitmap.createBitmap(fw + sw, fh > sh ? fh : sh, Config.ARGB_8888);
			Canvas canvas = new Canvas(newBitmap);
			canvas.drawBitmap(first, sw, 0, null);
			canvas.drawBitmap(second, 0, 0, null);
		} else if (direction == RIGHT) {
			newBitmap = Bitmap.createBitmap(fw + sw, fh > sh ? fh : sh, Config.ARGB_8888);
			Canvas canvas = new Canvas(newBitmap);
			canvas.drawBitmap(first, 0, 0, null);
			canvas.drawBitmap(second, fw, 0, null);
		} else if (direction == TOP) {
			newBitmap = Bitmap.createBitmap(sw > fw ? sw : fw, fh + sh, Config.ARGB_8888);
			Canvas canvas = new Canvas(newBitmap);
			canvas.drawBitmap(first, 0, sh, null);
			canvas.drawBitmap(second, 0, 0, null);
		} else if (direction == BOTTOM) {
			newBitmap = Bitmap.createBitmap(sw > fw ? sw : fw, fh + sh, Config.ARGB_8888);
			Canvas canvas = new Canvas(newBitmap);
			canvas.drawBitmap(first, 0, 0, null);
			canvas.drawBitmap(second, 0, fh, null);
		}
		return newBitmap;
	}

	/**
	 * 将Bitmap转换成指定大小
	 * 
	 * @param bitmap
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap createBitmapBySize(Bitmap bitmap, int width, int height) {
		return Bitmap.createScaledBitmap(bitmap, width, height, true);
	}

	/**
	 * Drawable 转 Bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmapByBD(Drawable drawable) {
		BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
		return bitmapDrawable.getBitmap();
	}

	/**
	 * Bitmap 转 Drawable
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Drawable bitmapToDrawableByBD(Bitmap bitmap) {
		Drawable drawable = new BitmapDrawable(bitmap);
		return drawable;
	}

	/**
	 * byte[] 转 bitmap
	 * 
	 * @param b
	 * @return
	 */
	public static Bitmap bytesToBimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	/**
	 * bitmap 转 byte[]
	 * 
	 * @param bm
	 * @return
	 */
	public static byte[] bitmapToBytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * 生成图片倒影
	 * 
	 * @param originalImage
	 * @return
	 */
	public static Bitmap createReflectedImage(Bitmap originalImage) {

		final int reflectionGap = 4;
		int width = originalImage.getWidth();
		int height = originalImage.getHeight();

		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);

		Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false);

		Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);

		Canvas canvas = new Canvas(bitmapWithReflection);

		canvas.drawBitmap(originalImage, 0, 0, null);

		Paint defaultPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);

		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.MIRROR);

		paint.setShader(shader);

		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));

		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);

		return bitmapWithReflection;
	}

	/**
	 * 
	 * @Title: compressImage
	 * @Description: 我们先看下质量压缩方法：
	 * @param @param image
	 * @param @return 设定文件
	 * @return Bitmap 返回类型
	 * @throws
	 */
	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	/**
	 * 
	 * @Title: getimage
	 * @Description: 图片按比例大小压缩方法（根据路径获取图片并压缩）
	 * @param @param srcPath
	 * @param @return 设定文件
	 * @return Bitmap 返回类型
	 * @throws
	 */
	private Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	/*
	 * 图片按比例大小压缩方法（根据Bitmap图片压缩）
	 */

	private Bitmap comp(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到bans中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}
}
